package com.toune.dltools.ui

import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.text.SpannableStringBuilder
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.LinearLayout
import android.widget.RelativeLayout
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.jaeger.library.StatusBarUtil
import com.tamsiree.rxkit.RxActivityTool
import com.tamsiree.rxkit.view.RxToast
import com.toune.dltools.R
import com.toune.dltools.dialog.LoadingDialog
import com.toune.dltools.view.title.DLBaseTitleView
import com.toune.dltools.view.title.DLCustomTitleView
import com.toune.permission.DLPermissionDialog
import com.toune.permission.DLPermissionUtil
import com.toune.permission.OnGrantedListener
import kotlinx.android.synthetic.main.activity_base.*
import java.lang.reflect.ParameterizedType


open abstract class DLBaseActivity<V : DLBaseViewModel> : AppCompatActivity() {

    val MMlayoutParams: LinearLayout.LayoutParams = LinearLayout.LayoutParams(
        LinearLayout.LayoutParams.MATCH_PARENT,
        LinearLayout.LayoutParams.MATCH_PARENT
    )

    var MWlayoutParams = LinearLayout.LayoutParams(
        RelativeLayout.LayoutParams.MATCH_PARENT,
        ViewGroup.LayoutParams.WRAP_CONTENT
    )
    var isSignOut = false//判断是不是双击返回按钮退出APP的页面
    var hideBack = false//隐藏返回按钮
    var isStatusBar = true //是否是沉浸式
    lateinit var context: Context
    lateinit var mViewModel: V
    var mRootView: View? = null //多布局根View
    var mTitleRootView: DLCustomTitleView? = null //标题的View
    private var exitTime: Long = 0
    private var isFirst = false
    var mTitleColor = DLActivityConfig.defTitleBgColor
    var whiteStatus = DLActivityConfig.isWhiteStatus

    /**
     * 创建一个Class的对象来获取泛型的class
     */
    private var clz: Class<V>? = null

    open fun getClz(): Class<V>? {
        if (clz == null) {
            clz =
                (this.javaClass.genericSuperclass as ParameterizedType?)!!.actualTypeArguments[0] as Class<V>?
        }
        return clz
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        context = this
        RxActivityTool.addActivity(this)
        mViewModel = ViewModelProviders.of(this).get(getClz()!!)
        val view = View.inflate(context, R.layout.activity_base, null)
        settingBeforSetContentView()
        //是否设置沉浸式
        if (isStatusBar) {
            setStatusBar()
        }
        setContentView(view)
        //插入标题控件
        if (titleStr.isNullOrEmpty()) { //标题隐藏
            baseTitleLv.visibility = View.GONE
        } else {  //标题显示
            baseTitleLv.visibility = View.VISIBLE
            baseTitleLv.removeAllViews()
            if (DLActivityConfig.useDefaultTitleView) {
                //使用自带控件
                mTitleRootView = DLBaseTitleView(this, baseTitleLv, titleStr, hideBack)
            } else {
                mTitleRootView = DLActivityConfig.customTitleView
            }
            mTitleRootView!!.reView(context, baseTitleLv, titleStr!!)
        }
        mRootView = View.inflate(context, layout, null)

        mRootRv.showContent(mRootView, MMlayoutParams)

        mViewModel.loadingSate.observe(this, Observer {
            if (it) showLoading() else hideLoading()
        })
        //一些初始化操作
        init(savedInstanceState)
        //一些业务逻辑
        initEventAndData()
    }

    /**
     * 在setContentView之前设置一些东西
     */
    open fun settingBeforSetContentView() {

    }

    /**
     * 显示用户隐私协议弹框
     * 直接使用自己的dialog
     */
    @RequiresApi(Build.VERSION_CODES.M)
    fun showUserPrivacyDialog(dialog: Dialog) {
        if (!DLPermissionUtil.isAppFirst(this)) {
            dialog.setCanceledOnTouchOutside(false)
            dialog.show()
        }
    }

    /**
     * 显示用户隐私协议弹框
     * 用默认的，设置contentSpan就行
     */
    @RequiresApi(Build.VERSION_CODES.M)
    fun showUserPrivacyDialog(contentSpan: SpannableStringBuilder?, vararg permissions: String) {
        if (!DLPermissionUtil.isAppFirst(this)) {
            showUserPrivacy(contentSpan, *permissions)
        }
    }

    /**
     * 用户隐私协议弹窗
     */
    private fun showUserPrivacy(contentSpan: SpannableStringBuilder?, vararg permissions: String) {
        var dialog = DLPermissionDialog(
            this,
            contentSpan,
            object : DLPermissionDialog.OnPermissionClickListener {
                override fun sureClickListener() {
                    userPrivacySureClick()
                }

                override fun cancelClickListener() {

                }
            },
            *permissions
        )
        dialog.setCanceledOnTouchOutside(false)
        dialog.show()
    }

    open fun userPrivacySureClick() {

    }

    /**
     * 设置这个页面需要请求的权限
     */
    @RequiresApi(Build.VERSION_CODES.M)
    fun showPermission(vararg permissions: String) {
        DLPermissionUtil.with(this).showPermissionDialog(*permissions)
    }

    /**
     * 显示用户隐私协议弹框
     */
    @RequiresApi(Build.VERSION_CODES.M)
    fun showPermission(onGrantedListener: OnGrantedListener, vararg permissions: String) {
        DLPermissionUtil.with(this).setOnGrantedClickListener(onGrantedListener)
            .showPermissionDialog(*permissions)
    }


    /**
     * 使用默认的title才生效
     * @param view View
     */
    fun addRightView(view: View): View? {
        if (DLActivityConfig.useDefaultTitleView) {
            return (mTitleRootView as DLBaseTitleView).addRightView(view)
        }
        return null
    }

    fun addRightView(str: String): View? {
        if (DLActivityConfig.useDefaultTitleView) {
            return (mTitleRootView as DLBaseTitleView).addRightTv(str)
        }
        return null
    }

    fun addRightView(imgId: Int): View? {
        if (DLActivityConfig.useDefaultTitleView) {
            return (mTitleRootView as DLBaseTitleView).addRightIv(imgId)
        }
        return null
    }

    fun removeRightView() {
        if (DLActivityConfig.useDefaultTitleView) {
            (mTitleRootView as DLBaseTitleView).removeRightView()
        }
    }

    /**
     * 设置沉浸式
     */
    private fun setStatusBar() {
        StatusBarUtil.setTranslucent(this);
        if (!whiteStatus) {
            StatusBarUtil.setDarkMode(this)
        } else {
            StatusBarUtil.setLightMode(this)
        }
    }

    abstract val layout: Int
    abstract val titleStr: String?

    /**
     * 返回按钮，可不实现
     */
    fun onBackIv() {
        if (mTitleRootView != null) {
            mTitleRootView!!.onBackIv(this)
        } else {
            RxActivityTool.finishActivity(this)
        }
    }

    fun setTitleStr(string: String?) {
        mTitleRootView!!.setTitleStr(string)
    }

    /**
     * 本Activity进行的跳转
     * @param clazz Class<Any>
     */
    fun startToActivity(clazz: Class<out Activity>) {
        RxActivityTool.skipActivity(this, clazz)
    }

    /**
     * 添加其他的model
     */
    inline fun <reified T : DLBaseViewModel> addViewModel(): T {
        return ViewModelProviders.of(this).get(T::class.java)
    }

    /**
     * 本Activity进行的带参数跳转
     * @param clazz Class<Any>
     * @param bundle Bundle
     */
    fun startToActivity(clazz: Class<out Activity>, bundle: Bundle) {
        RxActivityTool.skipActivity(this, clazz, bundle)
    }

    abstract fun init(savedInstanceState: Bundle?)
    abstract fun initEventAndData()

    //如果有自定义需求就用这个方法//如果有自定义需求就用这个方法
    lateinit var loadingDialog: LoadingDialog

    fun showLoading() {
        if (this::loadingDialog.isInitialized) {
            loadingDialog.show()
        } else {
            loadingDialog =
                LoadingDialog(this, DLActivityConfig.loadingColor, DLActivityConfig.loadingXml)
            loadingDialog.setOwnerActivity(this)
            loadingDialog.setCanceledOnTouchOutside(false)
            loadingDialog.show()
        }
    }

    fun hideLoading() {
        if (this::loadingDialog.isInitialized && !loadingDialog.ownerActivity!!.isDestroyed && loadingDialog.isShowing) {
            loadingDialog.dismiss()
        }
    }

    /**
     * 显示主内容
     */
    fun showContent() {
        mRootRv.showContent()
    }

    override fun onBackPressed() {
        if (isSignOut) {
            //连续按2次返回键退出
            if (System.currentTimeMillis() - exitTime > 2000) {
                RxToast.showToast("再按一次退出")
                exitTime = System.currentTimeMillis()
            } else {
                RxActivityTool.finishAllActivity()
            }
        } else {
            onBackIv()
        }
    }

}